#include "crc.h"
#include <QDebug>

std::unique_ptr <CalculatedCRC> CalculatedCRC::m_InStance = nullptr;
std::once_flag CalculatedCRC::m_Flag;

CalculatedCRC& CalculatedCRC::GetInstance()
{
    std::call_once(m_Flag,[](){
       m_InStance.reset(new CalculatedCRC());
    });
    return *m_InStance;
}
CalculatedCRC::CalculatedCRC() {

}

CalculatedCRC::~CalculatedCRC() {

}

//CRC 校验
QString CalculatedCRC::calculateCRC32(const QString &data)
{
    QByteArray byteArray = data.toUtf8();
    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.addData(byteArray);
    QByteArray hashResult = hash.result();
    QString crc = QString::fromLatin1(hashResult.toHex());
    return crc;
}

//CRC 验证
bool CalculatedCRC::verfyCRC32(const QString& dataWithCRC)
{
    int lastSpaceIndex = dataWithCRC.lastIndexOf(' ');
    QString receivedCRC = dataWithCRC.right(dataWithCRC.length() - lastSpaceIndex - 1);
    QString data = dataWithCRC.left(lastSpaceIndex);

    qDebug() << "  KeyWidget::verfyCRC32 receivedCRC: " << receivedCRC << " data： "<< data;
    QByteArray byteArrayData = data.toUtf8();

    QCryptographicHash hash(QCryptographicHash::Md5);
    hash.addData(byteArrayData);
    QByteArray hashResult = hash.result();

    QString calculatedCRC = QString::fromLatin1(hashResult.toHex());

    if (receivedCRC == calculatedCRC) {
        qDebug() << "CRC校验通过";
        return true;
    } else {
        qDebug() << "CRC校验失败";
        return false;
    }
}